#include "buffer.h"
#include <unistd.h>
#include <sys/uio.h>
ssize_t Buffer::readFd(int fd, int* saveErrno){

    char extraBuf[65526] = {0};      // 栈上的空间

    struct iovec vec[2];

    const size_t writeable = writeableBytes();  
    vec[0].iov_base = begin() + writeIndex_; 
    vec[0].iov_len = writeable;

    vec[1].iov_base = extraBuf;
    vec[1].iov_len = sizeof(extraBuf);


    const ssize_t n = readv(fd, vec, 2);
    if( n < 0){
        *saveErrno = errno;
    }else if(n <= writeable){
        writeIndex_ += n;
    }else{
        writeIndex_ = buffer_.size();
        append(extraBuf, n - writeable);
    }
    
    return n;
}


ssize_t Buffer::writeFd(int fd, int* saveErrno){
    ssize_t n = ::write(fd, peek(), writeableBytes());
    if(n < 0){
        *saveErrno = errno;
    }
    return n;
}
